package com.sencorsta.ids.game.http.common;

import com.alibaba.fastjson.JSONObject;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.http.HttpHandler;
import com.sencorsta.ids.core.tcp.socket.protocol.RpcMessage;
import com.sencorsta.ids.game.proto.GamePushRoomStatusByProto;
import com.sencorsta.ids.game.world.bean.World;
import com.sencorsta.ids.game.world.room.Room;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;

import java.util.Set;

import static com.sencorsta.ids.game.util.PushAndSaved.pushProto;

/**
* @description: 停止当前房间
* @author TAO
* @date 2020/1/6 5:52
*/
public class StopRoom extends HttpHandler {
    @Override
    public String doPost(ChannelHandlerContext ctx, FullHttpRequest request, JSONObject params) {
        Out.debug("------------------停止当前房间---------StopRoom-------------------");
        int gameId=params.getInteger("gameId");
        int roomId=params.getInteger("roomId");

        Out.debug("gameId",gameId);
        Out.debug("roomId",roomId);


        if (!World.getInstance().games.containsKey(gameId)){
            return error(54001,"游戏不存在");
        }
        if (!World.getInstance().games.get(gameId).rooms.containsKey(roomId)){
            return error(54002,"房间没有运行");
        }


        Room room=World.getInstance().games.get(gameId).rooms.get(roomId);
        if (room.isStop==true){
            return error(54003,"房间正在关闭中，无需再次关闭");
        }
        if (room.isStoped==true){
            return error(54004,"房间已经关闭，无需再次关闭");
        }


        //改变当前房间的状态--给前端显示屏蔽
        room.status=3;
        room.isStop=true;
        //外加推送
        GamePushRoomStatusByProto.PushRoomStatus.Builder push=GamePushRoomStatusByProto.PushRoomStatus.newBuilder();
        push.setRoomId(roomId);
        push.setGameId(gameId);
        push.setStatus(3);
        RpcMessage pushMsg=pushProto("", "push.roomStatus", push);
        room.broadcast(pushMsg,"proxy");


        Set<String> userList = World.getInstance().games.get(gameId).rooms.get(roomId).zoneUsers.keySet();//获取当前房间的所有玩家
        for (var user:userList){
            World.getInstance().leaveWorld(user);//将所有玩家提出
        }
        return success();
    }

    @Override
    public String doGet(ChannelHandlerContext ctx, FullHttpRequest request, JSONObject params) {
        return doPost(ctx, request, params);
    }

    @Override
    public String getPath() {
        return "/Game/StopRoom";
    }
}
